package org.jdpf.gui.rcp.neteditor.core.util;

import java.io.IOException;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.jdpf.core.kernel.logging.ILogger;
import org.jdpf.core.kernel.logging.LoggerFactory;
import org.jdpf.core.kernel.plugins.BundleToolBox;
import org.jdpf.gui.rcp.neteditor.core.elements.GraphicNet;
import org.osgi.framework.Bundle;
import org.xml.sax.SAXException;
import org.jdpf.core.kernel.logging.ILoggable;

public class GraphicNetLoader implements IGraphicInformationsHandler, ILoggable {

	private static final ILogger logger = LoggerFactory.getDefault()
			.getLogger();

	private static final String NET_SCHEMA = "JDPFNet.xsd";

	private Boolean logging = true;

	private SAXParserFactory factory;

	private String xmlFile;

	public GraphicNetLoader(String xmlFile) {
		this.xmlFile = xmlFile;

		factory = SAXParserFactory.newInstance();
		factory.setNamespaceAware(true);
		SchemaFactory schemaFactory = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema = null;
		try {
			Bundle netLoader = BundleToolBox.getDefault().getBundle(
					"org.jdpf.core.netloader");
			URL f = (URL) netLoader.findEntries("/", NET_SCHEMA, true)
					.nextElement();
			schema = schemaFactory.newSchema(f);
			factory.setSchema(schema);
			factory.setValidating(true);
		} catch (Exception e) {
			logger.error(this, e.getMessage());
		}
	}

	public void enableLogging(Boolean logging) {
		this.logging = logging;
	}

	public void computeBlocksPosition(GraphicNet gnet) {
		try {
			if (logging)
				logger.logMainPoint(this, xmlFile,
						"Graphic Net loading started.");
			SAXParser parser = factory.newSAXParser();
			parser.parse(xmlFile, new GraphicNetParserEventHandler(gnet));
			if (logging)
				logger.logMainPoint(this, xmlFile,
						"Graphic Net loading completed.");
		} catch (ParserConfigurationException e) {
			logger.error(this, e.getMessage());
		} catch (SAXException e) {
			logger.error(this, e.getMessage());
		} catch (IOException e) {
			logger.error(this, e.getMessage());
		} catch (Exception e) {
			logger.error(this, "Unable to load graphic net informations from "
					+ xmlFile + " because of: " + e.toString());
		}

	}
}
